#include "ui/ConfigPanel.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QCheckBox>
#include <QLineEdit>
#include <QListWidget>
#include <QTextEdit>
#include <QPushButton>
#include <QLabel>
#include <QScrollArea>
#include "ui/CustomScrollView.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QJsonArray>
#include <QIntValidator>

ConfigPanel::ConfigPanel(QWidget *parent)
    : QWidget(parent)
{
    setupUi();
}

ConfigPanel::~ConfigPanel() = default;

void ConfigPanel::setupUi()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    
    // 创建滚动区域
    CustomScrollView *scrollArea = new CustomScrollView;
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    
    // 创建滚动内容窗口
    QWidget *scrollContent = new QWidget;
    QVBoxLayout *contentLayout = new QVBoxLayout(scrollContent);
    contentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->setSpacing(12);
    
    // 混淆选项组
    QGroupBox *optionsGroup = new QGroupBox("混淆选项");
    QVBoxLayout *optionsLayout = new QVBoxLayout(optionsGroup);
    
    m_obfuscateClassesCheck = new QCheckBox("混淆类名");
    m_obfuscateClassesCheck->setChecked(true);
    optionsLayout->addWidget(m_obfuscateClassesCheck);
    
    m_obfuscatePropertiesCheck = new QCheckBox("混淆属性名");
    m_obfuscatePropertiesCheck->setChecked(true);
    optionsLayout->addWidget(m_obfuscatePropertiesCheck);
    
    m_obfuscateMethodsCheck = new QCheckBox("混淆方法名");
    m_obfuscateMethodsCheck->setChecked(true);
    optionsLayout->addWidget(m_obfuscateMethodsCheck);
    
    m_injectTrashCodeCheck = new QCheckBox("注入垃圾代码");
    m_injectTrashCodeCheck->setChecked(true);
    optionsLayout->addWidget(m_injectTrashCodeCheck);
    
    m_encryptStringsCheck = new QCheckBox("字符串加密（开发中）");
    m_encryptStringsCheck->setEnabled(false);
    optionsLayout->addWidget(m_encryptStringsCheck);
    
    contentLayout->addWidget(optionsGroup);
    
    // 命名规则组
    QGroupBox *namingGroup = new QGroupBox("命名规则");
    QGridLayout *namingLayout = new QGridLayout(namingGroup);
    
    namingLayout->addWidget(new QLabel("前缀:"), 0, 0);
    m_prefixEdit = new QLineEdit;
    m_prefixEdit->setPlaceholderText("留空则随机生成");
    namingLayout->addWidget(m_prefixEdit, 0, 1);
    
    namingLayout->addWidget(new QLabel("后缀:"), 1, 0);
    m_suffixEdit = new QLineEdit;
    m_suffixEdit->setPlaceholderText("留空则随机生成");
    namingLayout->addWidget(m_suffixEdit, 1, 1);
    
    namingLayout->addWidget(new QLabel("最小长度:"), 2, 0);
    m_minLengthEdit = new QLineEdit;
    m_minLengthEdit->setValidator(new QIntValidator(3, 20, this));
    m_minLengthEdit->setText("6");
    namingLayout->addWidget(m_minLengthEdit, 2, 1);
    
    namingLayout->addWidget(new QLabel("最大长度:"), 3, 0);
    m_maxLengthEdit = new QLineEdit;
    m_maxLengthEdit->setValidator(new QIntValidator(6, 30, this));
    m_maxLengthEdit->setText("12");
    namingLayout->addWidget(m_maxLengthEdit, 3, 1);
    
    contentLayout->addWidget(namingGroup);
    
    // 排除路径组
    QGroupBox *excludeGroup = new QGroupBox("排除路径");
    QVBoxLayout *excludeLayout = new QVBoxLayout(excludeGroup);
    
    m_excludeList = new QListWidget;
    m_excludeList->setMinimumHeight(150);
    m_excludeList->setAlternatingRowColors(true);
    
    // 添加默认排除路径
    QStringList defaultExcludes = {
        "Pods/",
        "build/",
        ".git/",
        "node_modules/",
        "*.framework/",
        "Third-Party/"
    };
    
    for (const QString &path : defaultExcludes) {
        QListWidgetItem *item = new QListWidgetItem(path);
        item->setForeground(Qt::gray);
        item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
        m_excludeList->addItem(item);
    }
    
    excludeLayout->addWidget(m_excludeList);
    
    QHBoxLayout *excludeInputLayout = new QHBoxLayout;
    
    m_browseExcludeButton = new QPushButton("选择文件夹");
    QIcon browseIcon;
    browseIcon.addFile(":/icons/folder_open.svg", QSize(), QIcon::Normal);
    browseIcon.addFile(":/icons/folder_open_gray.svg", QSize(), QIcon::Disabled);
    m_browseExcludeButton->setIcon(browseIcon);
    m_browseExcludeButton->setMinimumWidth(100);
    m_browseExcludeButton->setFixedHeight(28);
    m_browseExcludeButton->setEnabled(false);  // 默认禁用
    m_browseExcludeButton->setVisible(true);  // 确保初始可见
    connect(m_browseExcludeButton, &QPushButton::clicked, [this]() {
        QString dir = QFileDialog::getExistingDirectory(this, 
            "选择要排除的文件夹",
            QString(),
            QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
        
        if (!dir.isEmpty()) {
            // 获取相对路径或最后的文件夹名
            QFileInfo fileInfo(dir);
            QString relativePath = fileInfo.fileName() + "/";
            
            // 检查是否已存在
            bool exists = false;
            for (int i = 0; i < m_excludeList->count(); ++i) {
                if (m_excludeList->item(i)->text() == relativePath) {
                    exists = true;
                    break;
                }
            }
            
            if (!exists) {
                m_excludeList->addItem(relativePath);
                emit configChanged();
            }
        }
    });
    excludeInputLayout->addWidget(m_browseExcludeButton);
    
    m_fromProjectButton = new QPushButton("从项目选择");
    m_fromProjectButton->setToolTip("从左侧项目树中选择要排除的文件夹");
    m_fromProjectButton->setMinimumWidth(100);
    m_fromProjectButton->setFixedHeight(28);
    m_fromProjectButton->setEnabled(false);  // 默认禁用
    m_fromProjectButton->setVisible(true);  // 确保初始可见
    connect(m_fromProjectButton, &QPushButton::clicked, [this]() {
        emit requestExcludeFromProject();
    });
    excludeInputLayout->addWidget(m_fromProjectButton);
    
    excludeInputLayout->addStretch();
    
    m_removeExcludeButton = new QPushButton("移除");
    m_removeExcludeButton->setMinimumWidth(60);
    m_removeExcludeButton->setFixedHeight(28);
    m_removeExcludeButton->setEnabled(false);  // 默认禁用
    m_removeExcludeButton->setVisible(true);  // 确保初始可见
    m_removeExcludeButton->setProperty("warning", true);  // 设置为warning样式
    connect(m_removeExcludeButton, &QPushButton::clicked, [this]() {
        QListWidgetItem *currentItem = m_excludeList->currentItem();
        if (currentItem && (currentItem->flags() & Qt::ItemIsSelectable)) {
            delete currentItem;
            emit configChanged();
        }
    });
    excludeInputLayout->addWidget(m_removeExcludeButton);
    
    excludeLayout->addLayout(excludeInputLayout);
    
    contentLayout->addWidget(excludeGroup);
    
    // 类名白名单组
    QGroupBox *classWhitelistGroup = new QGroupBox("类名白名单");
    QVBoxLayout *classWhitelistLayout = new QVBoxLayout(classWhitelistGroup);
    
    QLabel *classWhitelistHint = new QLabel("每行输入一个不需要混淆的类名：");
    classWhitelistHint->setProperty("role", "hint");
    classWhitelistLayout->addWidget(classWhitelistHint);
    
    m_classWhitelist = new QTextEdit;
    m_classWhitelist->setPlaceholderText("UIViewController\nNSObject\nAppDelegate\nMyCustomClass");
    m_classWhitelist->setMaximumHeight(80);
    classWhitelistLayout->addWidget(m_classWhitelist);
    
    contentLayout->addWidget(classWhitelistGroup);
    
    // 属性白名单组
    QGroupBox *propertyWhitelistGroup = new QGroupBox("属性白名单");
    QVBoxLayout *propertyWhitelistLayout = new QVBoxLayout(propertyWhitelistGroup);
    
    QLabel *propertyWhitelistHint = new QLabel("每行输入一个不需要混淆的属性名：");
    propertyWhitelistHint->setProperty("role", "hint");
    propertyWhitelistLayout->addWidget(propertyWhitelistHint);
    
    m_propertyWhitelist = new QTextEdit;
    m_propertyWhitelist->setPlaceholderText("delegate\nframe\nbounds\ntag");
    m_propertyWhitelist->setMaximumHeight(80);
    propertyWhitelistLayout->addWidget(m_propertyWhitelist);
    
    contentLayout->addWidget(propertyWhitelistGroup);
    
    // 方法白名单组
    QGroupBox *methodWhitelistGroup = new QGroupBox("方法白名单");
    QVBoxLayout *methodWhitelistLayout = new QVBoxLayout(methodWhitelistGroup);
    
    QLabel *methodWhitelistHint = new QLabel("每行输入一个不需要混淆的方法名：");
    methodWhitelistHint->setProperty("role", "hint");
    methodWhitelistLayout->addWidget(methodWhitelistHint);
    
    m_methodWhitelist = new QTextEdit;
    m_methodWhitelist->setPlaceholderText("viewDidLoad\ninitWithFrame\ndealloc\ndidReceiveMemoryWarning");
    m_methodWhitelist->setMaximumHeight(80);
    methodWhitelistLayout->addWidget(m_methodWhitelist);
    
    contentLayout->addWidget(methodWhitelistGroup);
    
    // 添加弹簧
    contentLayout->addStretch();
    
    // 设置滚动区域
    scrollArea->setContentWidget(scrollContent);
    mainLayout->addWidget(scrollArea);
    
    // 连接信号
    connect(m_obfuscateClassesCheck, &QCheckBox::toggled, this, &ConfigPanel::configChanged);
    connect(m_obfuscatePropertiesCheck, &QCheckBox::toggled, this, &ConfigPanel::configChanged);
    connect(m_obfuscateMethodsCheck, &QCheckBox::toggled, this, &ConfigPanel::configChanged);
    connect(m_injectTrashCodeCheck, &QCheckBox::toggled, this, &ConfigPanel::configChanged);
    connect(m_encryptStringsCheck, &QCheckBox::toggled, this, &ConfigPanel::configChanged);
    connect(m_prefixEdit, &QLineEdit::textChanged, this, &ConfigPanel::configChanged);
    connect(m_suffixEdit, &QLineEdit::textChanged, this, &ConfigPanel::configChanged);
    connect(m_minLengthEdit, &QLineEdit::textChanged, this, &ConfigPanel::configChanged);
    connect(m_maxLengthEdit, &QLineEdit::textChanged, this, &ConfigPanel::configChanged);
    connect(m_classWhitelist, &QTextEdit::textChanged, this, &ConfigPanel::configChanged);
    connect(m_propertyWhitelist, &QTextEdit::textChanged, this, &ConfigPanel::configChanged);
    connect(m_methodWhitelist, &QTextEdit::textChanged, this, &ConfigPanel::configChanged);
}

ObfuscationConfig ConfigPanel::getObfuscationConfig() const
{
    ObfuscationConfig config;
    
    config.obfuscateClasses = m_obfuscateClassesCheck->isChecked();
    config.obfuscateProperties = m_obfuscatePropertiesCheck->isChecked();
    config.obfuscateMethods = m_obfuscateMethodsCheck->isChecked();
    config.injectTrashCode = m_injectTrashCodeCheck->isChecked();
    config.encryptStrings = m_encryptStringsCheck->isChecked();
    
    config.prefixPattern = m_prefixEdit->text();
    config.suffixPattern = m_suffixEdit->text();
    config.minNameLength = m_minLengthEdit->text().toInt();
    config.maxNameLength = m_maxLengthEdit->text().toInt();
    
    // 获取排除路径（跳过默认路径）
    for (int i = 0; i < m_excludeList->count(); ++i) {
        QListWidgetItem *item = m_excludeList->item(i);
        // 只添加用户自定义的路径（可选中的）
        if (item->flags() & Qt::ItemIsSelectable) {
            config.excludePaths.append(item->text());
        }
    }
    
    // 获取白名单
    QString classText = m_classWhitelist->toPlainText().trimmed();
    if (!classText.isEmpty()) {
        config.classWhitelist = classText.split('\n', Qt::SkipEmptyParts);
    }
    
    QString propertyText = m_propertyWhitelist->toPlainText().trimmed();
    if (!propertyText.isEmpty()) {
        config.propertyWhitelist = propertyText.split('\n', Qt::SkipEmptyParts);
    }
    
    QString methodText = m_methodWhitelist->toPlainText().trimmed();
    if (!methodText.isEmpty()) {
        config.methodWhitelist = methodText.split('\n', Qt::SkipEmptyParts);
    }
    
    return config;
}

QJsonObject ConfigPanel::getConfig() const
{
    QJsonObject config;
    
    config["obfuscateClasses"] = m_obfuscateClassesCheck->isChecked();
    config["obfuscateProperties"] = m_obfuscatePropertiesCheck->isChecked();
    config["obfuscateMethods"] = m_obfuscateMethodsCheck->isChecked();
    config["injectTrashCode"] = m_injectTrashCodeCheck->isChecked();
    config["encryptStrings"] = m_encryptStringsCheck->isChecked();
    
    config["prefixPattern"] = m_prefixEdit->text();
    config["suffixPattern"] = m_suffixEdit->text();
    config["minNameLength"] = m_minLengthEdit->text().toInt();
    config["maxNameLength"] = m_maxLengthEdit->text().toInt();
    
    QJsonArray excludePaths;
    for (int i = 0; i < m_excludeList->count(); ++i) {
        QListWidgetItem *item = m_excludeList->item(i);
        // 只添加用户自定义的路径
        if (item->flags() & Qt::ItemIsSelectable) {
            excludePaths.append(item->text());
        }
    }
    config["excludePaths"] = excludePaths;
    
    // 保存三个白名单
    config["classWhitelist"] = m_classWhitelist->toPlainText();
    config["propertyWhitelist"] = m_propertyWhitelist->toPlainText();
    config["methodWhitelist"] = m_methodWhitelist->toPlainText();
    
    return config;
}

void ConfigPanel::loadConfig(const QJsonObject &config)
{
    m_obfuscateClassesCheck->setChecked(config["obfuscateClasses"].toBool(true));
    m_obfuscatePropertiesCheck->setChecked(config["obfuscateProperties"].toBool(true));
    m_obfuscateMethodsCheck->setChecked(config["obfuscateMethods"].toBool(true));
    m_injectTrashCodeCheck->setChecked(config["injectTrashCode"].toBool(true));
    m_encryptStringsCheck->setChecked(config["encryptStrings"].toBool(false));
    
    m_prefixEdit->setText(config["prefixPattern"].toString());
    m_suffixEdit->setText(config["suffixPattern"].toString());
    m_minLengthEdit->setText(QString::number(config["minNameLength"].toInt(6)));
    m_maxLengthEdit->setText(QString::number(config["maxNameLength"].toInt(12)));
    
    m_excludeList->clear();
    
    // 先添加默认排除路径
    QStringList defaultExcludes = {
        "Pods/",
        "build/",
        ".git/",
        "node_modules/",
        "*.framework/",
        "Third-Party/"
    };
    
    for (const QString &path : defaultExcludes) {
        QListWidgetItem *item = new QListWidgetItem(path);
        item->setForeground(Qt::gray);
        item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
        m_excludeList->addItem(item);
    }
    
    // 再添加用户自定义的排除路径
    QJsonArray excludePaths = config["excludePaths"].toArray();
    for (const QJsonValue &value : excludePaths) {
        m_excludeList->addItem(value.toString());
    }
    
    // 加载三个白名单
    m_classWhitelist->setPlainText(config["classWhitelist"].toString());
    m_propertyWhitelist->setPlainText(config["propertyWhitelist"].toString());
    m_methodWhitelist->setPlainText(config["methodWhitelist"].toString());
}

void ConfigPanel::addExcludePath(const QString &path)
{
    // 检查是否已存在
    for (int i = 0; i < m_excludeList->count(); ++i) {
        if (m_excludeList->item(i)->text() == path) {
            return;  // 已存在，不重复添加
        }
    }
    
    // 添加新路径
    m_excludeList->addItem(path);
    emit configChanged();
}

void ConfigPanel::setProjectLoaded(bool loaded)
{
    // 启用/禁用所有与项目相关的按钮
    if (m_browseExcludeButton) {
        m_browseExcludeButton->setEnabled(loaded);
        m_browseExcludeButton->setVisible(true);  // 确保可见
        // 强制刷新样式
        m_browseExcludeButton->style()->unpolish(m_browseExcludeButton);
        m_browseExcludeButton->style()->polish(m_browseExcludeButton);
        m_browseExcludeButton->update();
    }
    if (m_fromProjectButton) {
        m_fromProjectButton->setEnabled(loaded);
        m_fromProjectButton->setVisible(true);  // 确保可见
        // 强制刷新样式
        m_fromProjectButton->style()->unpolish(m_fromProjectButton);
        m_fromProjectButton->style()->polish(m_fromProjectButton);
        m_fromProjectButton->update();
    }
    if (m_removeExcludeButton) {
        m_removeExcludeButton->setEnabled(loaded);
        m_removeExcludeButton->setVisible(true);  // 确保可见
        // 强制刷新样式
        m_removeExcludeButton->style()->unpolish(m_removeExcludeButton);
        m_removeExcludeButton->style()->polish(m_removeExcludeButton);
        m_removeExcludeButton->update();
    }
}